/**
 * member-admin.js - Reworked
 * A fresh rewrite to solve the persistent data display issue.
 * This version includes proper authentication and detailed diagnostics.
 */
document.addEventListener('DOMContentLoaded', function () {
    console.log('[会员重写诊断] 1. DOMContentLoaded event fired. Script is starting.');

    // --- Configuration ---
    const BASE_URL = '';
    const API_GET_ENDPOINT = `${BASE_URL}/api/member_getall`;
    const API_CREATE_ENDPOINT = `${BASE_URL}/api/member_create`;

    // --- DOM Element Caching ---
    const tableBody = document.querySelector('.main .card table tbody');
    const addMemberBtn = document.getElementById('add-member-btn');
    const addMemberModal = document.getElementById('add-member-modal');
    const cancelAddBtn = document.getElementById('cancel-add-btn');
    const confirmAddBtn = document.getElementById('confirm-add-btn');
    const addMemberForm = document.getElementById('add-member-form');
    const closeModalBtn = addMemberModal.querySelector('.close-btn');

    // --- Main Functions ---

    /**
     * Renders the provided member data into the table.
     * @param {Array} members - An array of member objects.
     */
    function renderTable(members) {
        console.log('[会员重写诊断] 5. renderTable function called.');
        tableBody.innerHTML = '';

        if (!members || members.length === 0) {
            console.log('[会员重写诊断] 5a. No members to render. Displaying "No data" message.');
            const row = tableBody.insertRow();
            const cell = row.insertCell();
            cell.colSpan = 6;
            cell.textContent = '暂无会员数据';
            cell.style.textAlign = 'center';
            return;
        }

        console.log(`[会员重写诊断] 5b. Rendering ${members.length} member(s).`);
        members.forEach((member, index) => {
            const row = tableBody.insertRow();
            const formatDate = (dateString) => dateString ? dateString.split('T')[0] : 'N/A';
            row.insertCell().textContent = member.id ?? 'N/A';
            row.insertCell().textContent = member.name ?? '未知姓名';
            row.insertCell().textContent = member.tel ?? 'N/A';
            row.insertCell().textContent = formatDate(member.date);
            row.insertCell().textContent = formatDate(member.expiration_date);
            const stateCell = row.insertCell();
            const stateSpan = document.createElement('span');
            stateSpan.textContent = member.state === 'active' ? '正常' : '已过期';
            stateSpan.className = member.state === 'active' ? 'status-ok' : 'status-danger';
            stateCell.appendChild(stateSpan);
        });
        console.log('[会员重写诊断] 6. Table rendering complete.');
    }

    /**
     * Fetches member data from the API and initiates rendering.
     */
    async function fetchAndRenderMembers() {
        console.log('[会员重写诊断] 3. fetchAndRenderMembers function called.');
        try {
            const token = localStorage.getItem('token');
            const headers = { 'Content-Type': 'application/json' };
            if (token) {
                headers['Authorization'] = 'Bearer ' + token;
                console.log('[会员重写诊断] 3a. 发现了token，已添加到请求头。');
            } else {
                console.log('[会员重写诊断] 3a. 未发现token。');
            }

            console.log(`[会员重写诊断] 3b. Fetching data from: ${API_GET_ENDPOINT}`);
            const response = await fetch(API_GET_ENDPOINT, { headers });
            console.log(`[会员重写诊断] 3c. API response status: ${response.status}`);

            if (!response.ok) {
                throw new Error(`API request failed with status ${response.status}`);
            }

            const data = await response.json();
            console.log('[会员重写诊断] 4. Raw data received from API:', data);

            const memberList = Array.isArray(data) ? data : (data.data || []);
            console.log('[会员重写诊断] 4a. Sanitized data to be used for rendering:', memberList);
            renderTable(memberList);

        } catch (error) {
            console.error('[会员重写诊断] CRITICAL ERROR during fetch or render:', error);
            renderTable([]);
        }
    }

    // --- Modal Handling ---
    function openModal() {
        if (addMemberModal) addMemberModal.style.display = 'block';
    }

    function closeModal() {
        if (addMemberModal) {
            addMemberModal.style.display = 'none';
            addMemberForm.reset();
        }
    }

    // --- Event Handlers ---
    async function handleAddMemberSubmit(event) {
        event.preventDefault();
        const nameInput = document.getElementById('member-name');
        const contactInput = document.getElementById('member-contact');

        const memberData = {
            name: nameInput.value.trim(),
            tel: contactInput.value.trim(),
            date: new Date().toISOString(),
            state: 'active',
            operation: 'no'
        };

        if (!memberData.name || !memberData.tel) {
            alert('姓名和联系方式不能为空！');
            return;
        }

        console.log('[会员操作] 准备新增会员:', memberData);

        try {
            const token = localStorage.getItem('token');
            const headers = { 'Content-Type': 'application/json' };
            if (token) {
                headers['Authorization'] = 'Bearer ' + token;
            }

            const response = await fetch(API_CREATE_ENDPOINT, {
                method: 'POST',
                headers: headers,
                body: JSON.stringify(memberData),
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({ message: '无法解析错误信息' }));
                throw new Error(`新增失败: ${errorData.message || response.statusText}`);
            }

            const result = await response.json();
            console.log('[会员操作] 新增成功:', result);
            alert('会员新增成功！');
            closeModal();
            fetchAndRenderMembers(); // Refresh the table

        } catch (error) {
            console.error('[会员操作] 新增会员时发生错误:', error);
            alert(`操作失败: ${error.message}`);
        }
    }
    
    /**
     * The entry point for the script.
     */
    function init() {
        console.log('[会员重写诊断] 2. init function called.');
        if (!tableBody || !addMemberBtn || !addMemberModal || !cancelAddBtn || !confirmAddBtn || !closeModalBtn) {
            console.error('[会员重写诊断] FATAL: Could not find one or more required DOM elements. Aborting.');
            return;
        }

        // Setup Event Listeners
        addMemberBtn.addEventListener('click', openModal);
        closeModalBtn.addEventListener('click', closeModal);
        cancelAddBtn.addEventListener('click', closeModal);
        confirmAddBtn.addEventListener('click', handleAddMemberSubmit);
        window.addEventListener('click', (event) => {
            if (event.target === addMemberModal) {
                closeModal();
            }
        });

        // Initial data fetch
        fetchAndRenderMembers();
    }

    // --- Script Start ---
    init();
});
